<template>
  <div>
    <div ref="editor" class="editor" :style="styles">
    </div>
    <el-upload
      class="avatar-uploader"
      ref="upload"
      action="#"
      :limit="1"
      :http-request="submitUpload"
      :auto-upload="true"
      :show-file-list="false"
      :file-list="fileList"
      :before-upload="beforeUpload">
    </el-upload>

  </div>
</template>

<script>
  import { saveFile } from '../../api/system/file'
  import axios from 'axios'
  import Quill from 'quill'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  import ImageResize from 'quill-image-resize-module'  // 图片缩放组件。
  import { ImageDrop } from 'quill-image-drop-module' // 图片拖动组件。
  Quill.register('modules/imageResize', ImageResize)
  Quill.register('modules/imageDrop', ImageDrop)

  export default {
    name: 'Editor',
    props: {
      /* 编辑器的内容 */
      value: {
        type: String,
        default: '',
      },
      /* 高度 */
      height: {
        type: Number,
        default: null,
      },
      /* 最小高度 */
      minHeight: {
        type: Number,
        default: null,
      },
    },
    data () {
      return {
        Quill: null,
        currentValue: '',
        fileList: [],
        accept: ['txt', 'png', 'jpg', 'zip', 'ppt'],
        filename: '',
        files: '',
        file: {
          url: null,
          type: '',
          fileName: undefined,
          size: undefined,
        },
        options: {
          theme: 'snow',
          bounds: document.body,
          debug: 'warn',
          modules: {
            // 工具栏配置
            toolbar: {
              container: [
                ['bold', 'italic', 'underline', 'strike'], //加粗，斜体，下划线，删除线
                ['blockquote',
                  'code-block'
                ], //引用，代码块
                [{ 'header': 1 }, { 'header': 2 }], // 标题，键值对的形式；1、2表示字体大小
                [{ 'list': 'ordered' }, { 'list': 'bullet' }], //列表
                [{ 'script': 'sub' }, { 'script': 'super' }], // 上下标
                [{ 'indent': '-1' }, { 'indent': '+1' }], // 缩进
                [{ 'direction': 'rtl' }], // 文本方向
                [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }], //几级标题
                [{ 'color': [] }, { 'background': [] }], // 字体颜色，字体背景颜色
                [{ 'font': [] }], //字体
                [{ 'align': [] }], //对齐方式
                ['clean'], //清除字体样式
                ['link', 'image', 'video'] //上传图片、上传视频
              ],
              // 监听图片上传点击事件
              handlers: {
                'image': function (value) {
                  if (value) {
                    // upload点击上传事件
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false)
                  }
                }
              },
            },

            imageResize: {
              displayStyles: {
                backgroundColor: 'black',
                border: 'none',
                color: 'white'
              },
              modules: ['Resize', 'DisplaySize', 'Toolbar']
            }
          },
          imageDrop: true,
          placeholder: '请输入内容',
          readOnly: false,
        },
      }
    },
    computed: {
      styles () {
        let style = {}
        if (this.minHeight) {
          style.minHeight = `${this.minHeight}px`
        }
        if (this.height) {
          style.height = `${this.height}px`
        }
        style.width = '100%'
        return style
      },
    },
    watch: {
      value: {
        handler (val) {
          if (val !== this.currentValue) {
            this.currentValue = val === null ? '' : val
            if (this.Quill) {
              this.Quill.pasteHTML(this.currentValue)
            }
          }
        },
        immediate: true,
      },
    },
    mounted () {
      this.init()
    },
    beforeDestroy () {
      this.Quill = null
    },
    methods: {
      init () {
        const editor = this.$refs.editor
        this.Quill = new Quill(editor, this.options)
        this.Quill.pasteHTML(this.currentValue)
        this.Quill.on('text-change', (delta, oldDelta, source) => {
          const html = editor.children[0].innerHTML
          const text = this.Quill.getText()
          const quill = this.Quill
          this.currentValue = html
          this.$emit('input', html)
          this.$emit('on-change', {
            html,
            text,
            quill
          })
        })
        this.Quill.on('text-change', (delta, oldDelta, source) => {
          this.$emit('on-text-change', delta, oldDelta, source)
        })
        this.Quill.on('selection-change', (range, oldRange, source) => {
          this.$emit('on-selection-change', range, oldRange, source)
        })
        this.Quill.on('editor-change', (eventName, ...args) => {
          this.$emit('on-editor-change', eventName, ...args)
        })
      },
      //文件格式大小检验
      beforeUpload (file) {
        console.log(file)
        this.files = file
        this.file.fileName = this.filename = file.name
        this.file.type = file.name.split('.')[1]
        this.file.size = file.size
        const extension = this.file.type.toLowerCase()
        const isLt5M = file.size / 1024 / 1024 < 100
        if (!isLt5M) {
          this.$message.warning('上传文件大小不能超过 5MB!')
          this.filename = ''
          file = ''
          return false
        }
      },
      onClose () {
        //清空当前弹窗数据
        this.filename = ''
        this.files = ''
      },
      //文件上传
      submitUpload () {
        if (this.filename === '') {
          this.$message.warning('请选择要上传的文件！')
          return false
        }
        const loading = this.$loading({
          lock: true,
          text: '文件上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        let fileFormData = new FormData()
        //file是对接名 和接口接收实体对象名一样，files就是要传的文件
        fileFormData.append('file', this.files)
        axios({
          url: '/api/uploadFile',
          method: 'post',
          data: fileFormData
        }).then(res => {
          if (res) {
            const dt = {}
            dt.url = res.data.data.file.url
            let quill = this.Quill
            // 获取光标所在位置
            let length = quill.selection.savedRange.index
            // 插入图片  dt.url为服务器返回的图片地址
            quill.insertEmbed(length, 'image', dt.url)
            // 调整光标到最后
            quill.setSelection(length + 1)
            this.$message.success('上传成功!')
            loading.close()
            this.file = res.data.data.file
            this.addFile()
            this.$emit('Fresh')
            this.onClose()
          } else {
            loading.close()
          }
        })
        /* setTimeout(() => {
           loading.close()
         }, 5000)*/
      },

      async addFile () {
        await saveFile(this.file)
      },
    },
  }
</script>

<style>
  .editor, .ql-toolbar {
    white-space: pre-wrap !important;
    line-height: normal !important;
  }

  .avatar-uploader {
    line-height: normal;
    position: relative;
    font-size: 14px;
  }

  .ql-editor p, .ql-editor ol, .ql-editor ul, .ql-editor pre, .ql-editor blockquote, .ql-editor h1, .ql-editor h2, .ql-editor h3, .ql-editor h4, .ql-editor h5, .ql-editor h6 {
    margin: 0;
    padding: 0;
    counter-reset: list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9;
  }

  .ql-snow .ql-tooltip[data-mode="link"]::before {
    content: "请输入链接地址:";
  }

  .ql-snow .ql-tooltip.ql-editing a.ql-action::after {
    border-right: 0;
    content: "保存";
    padding-right: 0;
  }

  .ql-snow .ql-tooltip[data-mode="video"]::before {
    content: "请输入视频地址:";
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item::before {
    content: "14px";
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
    content: "10px";
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
    content: "18px";
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
    content: "32px";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item::before {
    content: "文本";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
    content: "标题1";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
    content: "标题2";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
    content: "标题3";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
    content: "标题4";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
    content: "标题5";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
    content: "标题6";
  }

  .ql-snow .ql-picker.ql-font .ql-picker-label::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item::before {
    content: "标准字体";
  }

  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
    content: "衬线字体";
  }

  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
    content: "等宽字体";
  }
</style>
